import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';

const initMethods = {
  initCube: (canvas) => {
    // const canvas = document.querySelector('#c');
    // 1.创建渲染器负责将你提供的所有数据渲染绘制到canvas上
    const renderer = new THREE.WebGLRenderer({antialias: true, canvas});

    // 2、创建相机
    const fov = 75;
    const aspect = 2;  // 相机默认值
    const near = 0.1;
    const far = 5;
    const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
    // 定义相机的初始位置
    camera.position.z = 3;

    // 3.创建场景 我们添加的模型需要放入场景里面
    const scene = new THREE.Scene();
    scene.background = new THREE.Color("white");

    // 4.定义一个集几何体
    const boxWidth = 1;
    const boxHeight = 1;
    const boxDepth = 1;
    const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

    // 4.1 定义几何体材质 MeshBasicMaterial材质不会受到灯光的影响。我们将他改成会受灯光影响的MeshPhongMaterial材质
    // const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
    // const material = new THREE.MeshPhongMaterial({color: 0x44aa88});

    // 5.定义网格(Mesh)它包含了：
    // 几何体(Geometry)(物体的形状)
    // 材质(Material)(如何绘制物体，光滑还是平整，什么颜色，什么贴图等等)
    // 对象在场景中相对于他父对象的位置、朝向、和缩放。下面的代码中父对象即为场景对象
    // const cube = new THREE.Mesh(geometry, material);

    // 加入到场景里面展示
    // scene.add(cube);

    const cubes = [
      makeInstance(geometry, 0x44aa88,  0),
      makeInstance(geometry, 0x8844aa, -2),
      makeInstance(geometry, 0xaa8844,  2),
    ];

    // 最后把东西渲染出来
    renderer.render(scene, camera);

    const controls = new OrbitControls(camera, canvas);
    controls.target.set(0, 0, 0);

    // 6.引入循环函数让立方体旋转起来
    function render(time) {
      controls.update();
      time *= 0.001;  // 将时间单位变为秒
      cubes.forEach((cube, ndx) => {
        const speed = 1 + ndx * .1;
        const rot = time * speed;
        cube.rotation.x = rot;
        cube.rotation.y = rot;
      });
      renderer.render(scene, camera);

      requestAnimationFrame(render);
    }
    requestAnimationFrame(render);

    // 7.引入灯光，使立方体看起来更有效果
    {
      const color = 0xFFFFFF;
      const intensity = 3;
      const light = new THREE.DirectionalLight(color, intensity);
      light.position.set(-1, 2, 4);
      scene.add(light);
    }


    // 通用方法创建立方体
    function makeInstance(geometry, color, x) {
      const material = new THREE.MeshPhongMaterial({color});
      const cube = new THREE.Mesh(geometry, material);
      scene.add(cube);

      cube.position.x = x;

      return cube;
    }
  }
}

export default initMethods;